<template lang="pug">
div
  div.kalix-search
    div.kalix-search-hd
      i.iconfont.icon-query
      | {{title}}
    div.kalix-search-bd
      el-form.search-container(ref="searchForm" v-bind:model="form" v-bind:inline="true")
        slot(name="searchFormSlot")
          el-form-item(v-for="item in searchFields" v-bind:label="item.label" v-bind:prop="item.prop" v-bind:key="item.prop")
            el-select(v-if="item.type==='select'" v-model="form[item.prop]" v-bind:class="bindCls(item.cls)" v-bind:data-type="item.dataType" v-bind:clearable="item.clearable")
              el-option(v-for="option in item.options" v-bind:key="option.value" v-bind:label="option.label" v-bind:value="option.value")
            el-input-number(v-else-if="item.type==='number'" v-model="form[item.prop]" v-bind:class="bindCls(item.cls)" v-bind:data-type="item.dataType")
            kalix-tree2.inline(v-else-if="item.type==='tree'" v-model="form[item.prop]" v-bind:treeDataURL="item.treeDataURL" v-bind:parentNodeId="item.parentNodeId" v-bind:isAll="item.isAll")
            kalix-date-picker(v-else-if="item.type==='date'" v-model="form[item.prop]")
            kalix-date-picker(v-else-if="item.type==='year'" v-model="form[item.prop]" type="year")
            kalix-datetime-picker(v-else-if="item.type==='datetime'" v-model="form[item.prop]")
            kalix-dict-select(v-else-if="item.type==='dict'" v-bind:appName="item.appName" v-bind:dictType="item.dictType" v-model="form[item.prop]")
            kalix-object-select2(v-else-if="item.type==='objSelect'" v-model="form[item.prop]" v-bind:objectsUrl="item.selectUrl" v-bind:label="item.value")
            Kalix-map-select(v-else-if="item.type==='map'" v-bind:appName="item.appName" v-bind:prop="item.prop" v-bind:selectUrl="item.selectUrl" v-model="form[item.prop]"
            v-bind:selectedOptions="item.options" v-on:getProp="getProp" v-on:input="getSelectValue" v-bind:stopChange="item.stopChange")
            input(v-else-if="item.type==='inputHidden'" v-model="form[item.prop]" type="hidden")
            el-input(v-else v-model="form[item.prop]")
        el-form-item
          el-button(type="primary" v-on:click="onSubmitClick")
            i.iconfont.icon-query
            | 查询
          el-button(type="success" v-on:click="onResetClick")
            i.iconfont.icon-reset
            | 重置

  el-transfer.kalix-transfer(data-kalix-transfer="kalix-transfer"
    v-bind:targetURL="targetURL"
    v-bind:sourceURL="sourceURL"
    v-bind:targetID="targetID"
    v-bind:sourceType="sourceType"
    v-bind:searchType="searchType"
    v-bind:searchFields="searchFields"
    v-model="userChecked"
    style="width:100%" filterable
    v-bind:titles="['可选项', '已选项']"
    v-bind:footer-format="{noChecked: '${total}', hasChecked: '${checked}/${total}'}"
    v-bind:data="dataList"
    v-on:change="handleChange")
</template>

<script>
  /* eslint-disable keyword-spacing */

  import EventBus from './eventbus'
  import {strToUnicode} from './unicode-convert'
  import {isEmptyObject} from './util'
  import {ON_SEARCH_BUTTON_CLICK} from './event.toml'

  export default {
    name: 'kalix-search-transfer',
    props: {
      targetURL: {
        type: String
      },
      sourceURL: {
        type: String
      },
      targetID: {
        type: Number
      },
      sourceType: {
        type: String
      },
      searchType: {
        type: String
      },
      bizSearch: { // 使用的搜索组件名称
        type: String
      },
      noSearchParam: {
        type: Boolean,
        default: false
      },
      bizKey: {
        type: String,
        default: ''
      },
      searchForm: {
        type: Object
      },
      title: {
        type: String,
        default: ''
      },
      searchFields: { // 搜索查询的字段
        type: Array
      },
      formRules: null
    },
    data() {
      return {
        userList: [],
        dataList: [],
        userIds: [],
        ids: [],
        centerDialogVisible: false,
        userChecked: [],
        form: {},
        isSearch: false,
        queryStrs: {}
      }
    },
    created() {
      this._currentForm()
    },
    mounted() {
      // 调用初始化数据的方法
      this.getData()
    },
    components: {},
    computed: {
      searchCls() {
        // console.log('BBBBBBBBBBBBBBBBBBBBBBBB', this.bizKey)
        return 'kalix-search-' + this.bizKey
      }
    },
    methods: {
      refresh() { // 刷新表格数据
        console.log('[kalix] ' + this.title + ' refresh is trigger!')
      //  this.getData()
      },
      // 初始化数据
      getData(searchObjAll) {
        this.userList = []
        this.dataList = []
        let params = {}
        if(searchObjAll != null) {
          params = {
            jsonStr: searchObjAll.jsonStr
          }
        }
        this.axios.get(this.sourceURL, {
          params: params
        }).then(response => {
          this.userList = response.data.data
          for (let i = 0; i < this.userList.length; i++) {
            this.dataList.push({
              key: this.userList[i].id,
              label: this.userList[i].cnName
            })
          }
          this.ids[0] = this.targetID.toString()
          this.getCheckedUsers()
        })
      },
      // 获取已有记录的id
      getCheckedUsers() {
        let userCheckedUrl = this.targetURL + '/' + this.targetID + '/' + this.searchType
        this.axios.get(userCheckedUrl, {}).then(response => {
          if (response.data && response.data.length) {
            this.userChecked = response.data
            this.userIds = this.userChecked
          }
        })
      },
      // 选取用户之后调用的方法
      handleChange(value, direction, movedKeys) {
        if (direction === 'right') {
          this.userIds = this.userIds.concat(movedKeys)
        } else if (direction === 'left') {
          let tempId = []
          let m = 0
          for (let i = 0; i < this.userIds.length; i++) {
            let isHave = false
            for (let j = 0; j < movedKeys.length; j++) {
              if (this.userIds[i] === movedKeys[j]) {
                isHave = true
              }
            }
            if (!isHave) {
              tempId[m] = this.userIds[i]
              m++
            }
          }
          this.userIds = tempId
        }
      },
      onSearchClick(_searchParam) { // 查询按钮点击事件
        console.log('[kalix] base table search clicked')
        // 设置searchparam
        this.noSearchParam = false
        // 兼容多个baseTable同时使用情况，用bizKey区分具体查询
        if (_searchParam.bizKey) {
          this.searchParam = _searchParam.searchObj
          if (_searchParam.bizKey === this.bizKey) {
            this.refresh()
          }
        } else {
          this.searchParam = _searchParam
          this.refresh()
        }
        // 添加点击查询按钮之后的外部事件处理
        // this.$emit('afterSearch', this.bizKey)
      },
      bindFormDataType(e) {
        this.formDataType[e.prop] = e.dataType || e.type || 'string'
        this.formDataField[e.prop] = e.field || null
      },
      bindCls(label) {
        if (label) {
          return label.length > 0 ? `${this.bizKey}-${label}` : ''
        }
        return ''
      },
      _currentForm() {
        this.isSearchFrom = false
        this.formDataType = {}
        this.formDataField = {}
        if (!isEmptyObject(this.searchForm)) { // 是否传入 searchForm
          this.form = this.searchForm
          this.isSearchFrom = true
        } else {
          this.searchFields.forEach(item => {
            this.bindFormDataType(item)
            if (item.defaultVal) {
              this.$set(this.form, item.prop, item.defaultVal)
            } else {
              this.$set(this.form, item.prop, null)
            }
          })
        }
      },
      // 提交查询
      onSubmitClick() {
        this.$refs.searchForm.validate((valid) => {
          if (valid) {
            let requestDatas = []
            for (let item in this.form) {
              const itemVal = this.form[item]
              if (this.isSearchFrom) { // 如果有 SearchFrom 传入
                let dataType = typeof itemVal
                let field = item
                let docItems = document.getElementsByClassName(`${this.bizKey}-${item}`) // 根据 bizKey 和 v-model名 查找 dom 标签
                if (docItems && docItems.length === 1) {
                  //  如果 docItems 存在并且只有一个，获取当前字段的数据类型并赋值给 dataType
                  let docItem = docItems[0]
                  dataType = docItem.getAttribute('data-type')
                  field = docItem.getAttribute('field')
                  if (field && itemVal.length) {
                    let key = `"${field}"` // 绑定 查询 key
                    let val = `${itemVal}` // 绑定 查询 value
                    switch (dataType) {
                      case 'string':
                        //  如果 dataType 是 String 格式，key 和 val 增加双引号
                        key = `"%${field}%"`
                        if (this.isChinese(itemVal)) {
                          val = `"${strToUnicode(itemVal)}"`
                        } else {
                          val = `"${itemVal}"`
                        }
                        break
                      case 'datetime':
                        //  如果 dataType 是 Datetime 格式，val 增加双引号
                        key = `"${field}"`
                        val = `"${itemVal}"`
                        break
                      case 'orgTree':
                        val = `${itemVal}`
                        break
                    }
                    requestDatas.push(`${key}: ${val}`)
                  }
                }
              } else {
                if (itemVal) {
                  let field = item
                  let key = `"${field}"` // 绑定 查询 key
                  let val = `"${itemVal}"` // 绑定 查询 value
                  if (this.formDataField[item]) {
                    key = `"${this.formDataField[item]}"`
                  } else if (this.formDataType[item] === 'string') {
                    key = `"%${field}%"`
                  } else {
                    key = `"${this.sourceType}"`
                  }
                  switch (this.formDataType[item]) {
                    case 'string':
                      if (this.isChinese(itemVal)) {
                        val = `"${strToUnicode(itemVal)}"`
                      }
                      break
                    case 'number':
                      val = `${itemVal}`
                      break
                  }
                  requestDatas.push(`${key}: ${val}`)
                }
              }
            }
            let searchObj = {}
            if (requestDatas.length > 0) {
              searchObj.jsonStr = `{${requestDatas.join(',')}}`
            }
            this.isSearch = true
            // 兼容多个basetable查询情况
            let searchObjAll = {}
            if (this.bizKey) {
              searchObjAll.searchObj = searchObj
              searchObjAll.bizKey = this.bizKey
            } else {
              searchObjAll = searchObj
            }
            this.getData(searchObjAll)
          } else {
            console.log('ERR')
          }
        })
      },
      // 重置搜索框
      onResetClick() {
        this.$refs.searchForm.resetFields()
        if (this.isSearch) {
          EventBus.$emit(ON_SEARCH_BUTTON_CLICK, {})
          this.isSearch = false
        }
      },
      // 是否是数字
      isNumberData(_data) {
        const regNumber = /^[0-9]+.?[0-9]*$/
        return regNumber.test(_data)
      },
      isChinese(str) {
        let strExp = new RegExp(/^[\u4E00-\u9FA5]+$/)
        if (strExp.test(str)) {
          return true
        }
        return false
      },
      getProp(val) {
        this.$emit('getProp', val)
      },
      getSelectValue(val) {
        this.$emit('selectVal', val)
      }
    }
  }
</script>

<style lang="stylus">
  .kalix-transfer
    text-align center
    .el-checkbox
      display block
      text-align left
      & + .el-checkbox
        margin-left 0
    .el-transfer-panel__filter
      width auto !important

  .transfer-footer
    margin-left: 20px;
    padding: 6px 5px;

  .el-transfer__button
    color #fff
    background-color #409eff
    &.is-disabled
    &:hover
      border 1px solid #dcdfe6
      background-color #f5f7fa
      color #c0c4cc

  .kalix-transfer[data-kalix-transfer]
    .el-transfer__button
      color #fff
      background-color #409eff
      &.is-disabled
      &:hover
        border 1px solid #dcdfe6
        background-color #f5f7fa
        color #c0c4cc
</style>
